﻿using AutoMapper;
using B.S.Procurement.Domain;
using B.S.Procurement.Error;
using B.S.Procurement.Read.Api.Application.Command.ClientCommand;
using MediatR;
using SqlSugar;

namespace B.S.Procurement.Read.Api.Application.CommandHander.ClientCommandHander
{
    public class QueryClientCommandHander : IRequestHandler<QueryClientCommand, ApiPaging<List<Client>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public QueryClientCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiPaging<List<Client>>> Handle(QueryClientCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<List<Client>> result = new ApiPaging<List<Client>>();

            var item = await db.Queryable<Client>().Where(x => x.Del == false).ToListAsync();

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(x => x.ClientId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            result.Code = ApiEnum.success;
            result.Msg = "查询产品信息成功";
            result.Data = item;

            return result;
        }
    }
}
